from flask import request, jsonify, Blueprint
from numpy import *

from slewing.extension import db
from slewing.models import Dev

dev_bp = Blueprint('device', __name__)


@dev_bp.route('/get_distance/<string:macID>', methods=['GET'])
def get_distance(macID):
    """请求蓝牙节点设备与各网关的距离"""
    dev = Dev.query.filter_by(mac=macID.upper()).first()
    if dev:
        data = {
            "d1": dev.d1,
            "d2": dev.d2,
            "d3": dev.d3,
        }
        return jsonify(data)
    return jsonify(message="mac id error"), 400


@dev_bp.route('/get_location/<string:macID>', methods=['GET'])
def get_location(macID):
    """请求蓝牙节点设备的室内位置"""
    dev = Dev.query.filter_by(mac=macID.upper()).first()
    if dev:
        d1, d2, d3 = dev.d1, dev.d2, dev.d3
        x1, x2, x3 = dev.gateway1[0], dev.gateway2[0], dev.gateway3[0]
        y1, y2, y3 = dev.gateway1[1], dev.gateway2[1], dev.gateway3[1]

        A = matrix([[2 * (x2 - x1), 2 * (y2 - y1)],
                    [2 * (x3 - x2), 2 * (y3 - y2)]])

        B = matrix([[d1 ** 2 - d2 ** 2 - (x1 ** 2 + y1 ** 2) + (x2 ** 2 + y2 ** 2)],
                    [d2 ** 2 - d3 ** 2 - (x2 ** 2 + y2 ** 2) + (x3 ** 2 + y3 ** 2)]])

        X = (A.T * A).I * A.T * B
        location = X.tolist()
        print(X)
        return jsonify({"x": round(location[0][0], 2), "y": round(location[1][0], 2)})
        # import sympy
        # x = sympy.Symbol('x')
        # y = sympy.Symbol('y')
        #
        # location = sympy.solve([(x - dev.gateway1[0]) ** 2 + (y - dev.gateway1[1]) ** 2 - d1 ** 2,
        #                         (x - dev.gateway2[0]) ** 2 + (y - dev.gateway2[1]) ** 2 - d2 ** 2,
        #                         (x - dev.gateway3[0]) ** 2 + (y - dev.gateway3[1]) ** 2 - d3 ** 2], [x, y])
        #
        # return jsonify(json.dumps(location))
    return jsonify(message="mac id error"), 400


gateList = ['E0E2E69C2DB0', 'C45BBE8E574C', 'C45BBE951298']


@dev_bp.route('/update', methods=['POST'])
def dev_update():
    """设备信息上报"""
    gateway = request.json.get("mac")
    if gateway == gateList[0]:
        for device in request.json.get("devices"):
            print("gateway:{}, mac:{}, rssi:{}".format(gateway, device[1], device[2]))
            dev = Dev.query.filter_by(mac=device[1]).first()
            dev.d1 = dev.set_distance(device[2])
            db.session.commit()

    if gateway == gateList[1]:
        for device in request.json.get("devices"):
            print("gateway:{}, mac:{}, rssi:{}".format(gateway, device[1], device[2]))
            dev = Dev.query.filter_by(mac=device[1]).first()
            dev.d2 = dev.set_distance(device[2])
            db.session.commit()

    if gateway == gateList[2]:
        for device in request.json.get("devices"):
            print("gateway:{}, mac:{}, rssi:{}".format(gateway, device[1], device[2]))
            dev = Dev.query.filter_by(mac=device[1]).first()
            dev.d3 = dev.set_distance(device[2])
            db.session.commit()

    return jsonify(message="succeeded")
